//
//  BLTool.m
//  Byelone
//
//  Created by Qi Liu on 2021/1/31.
//

#import "BLTool.h"
#import "AliyunOSSiOS.h"
#import "BLLoginController.h"
#import "BLInfoAvatarController.h"
#import "BLInfoInputController.h"



#define pathDic @{@(0):@"avatar",@(1):@"photowall",@(2):@"moment",@(3):@"im",@(4):@"photo"}

//UpLoadImageType_Avatar,//头像上传
//UpLoadImageType_Photowall,
//UpLoadImageType_Moment,
//UpLoadImageType_IM,
//UpLoadImageType_Photo,
@implementation BLTool

//阿里云图片上传

+(NSString *)getUpPathWithType:(UpLoadImageType)type{
    return [pathDic objectForKey:@(type)];
}


+(CGSize)getGIFImageSizeWithData:(NSData *)data
{
    
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}

+(void)upLoadImageArray:(NSArray*)imageArray type:(UpLoadImageType)type success:(void(^)(NSArray *_Nonnull urlArray))success failure:(void(^)(NSString*_Nonnull errorString))failure{
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.bl.pospicture", DISPATCH_QUEUE_CONCURRENT);
    //将image转成Data
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:BL_STRING([BLUserManager shareUser].AccessKeyId) secretKeyId:BL_STRING([BLUserManager shareUser].AccessKeySecret) securityToken:BL_STRING([BLUserManager shareUser].SecurityToken)];
    
    OSSClient*client = [[OSSClient alloc]initWithEndpoint:BL_ALI_ENDPOINT credentialProvider:credential];
    
    __block NSMutableArray * array = [NSMutableArray array];
    // 创建信号量，并且设置值为10
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    for (int i = 0; i < imageArray.count; i++) {
        
        dispatch_group_async(group, queue, ^{
    
            NSString * iamgeType = @"png";
            NSData *data;
            __block NSMutableDictionary * dic = [NSMutableDictionary dictionary];
            if ([[imageArray objectAtIndex:i] isKindOfClass:[UIImage class]]) {
                UIImage * image = [imageArray objectAtIndex:i];
                CGFloat weight = CGImageGetWidth(image.CGImage);
                CGFloat height = CGImageGetHeight(image.CGImage);
                [dic setValue:@((int)weight) forKey:@"weight"];
                [dic setValue:@((int)height) forKey:@"height"];
                data = UIImagePNGRepresentation(image);
                
            }else if ([[imageArray objectAtIndex:i] isKindOfClass:[NSData class]]){
                
                data = [imageArray objectAtIndex:i];
                
            }else if([[imageArray objectAtIndex:i] isKindOfClass:[BLImageModel class]]){
                
                BLImageModel * imageModel = [imageArray objectAtIndex:i];
                if (imageModel.isGif) {
                    iamgeType = @"gif";
                    UIImage * image =  imageModel.image;
                    CGFloat weight = CGImageGetWidth(image.CGImage);
                    CGFloat height = CGImageGetHeight(image.CGImage);
                    [dic setValue:@((int)weight) forKey:@"weight"];
                    [dic setValue:@((int)height) forKey:@"height"];
                    data = imageModel.imageData;
                }else if (imageModel.isVideo){
                    iamgeType = @"mp4";
                    UIImage * image =  imageModel.image;
                    CGFloat weight = CGImageGetWidth(image.CGImage);
                    CGFloat height = CGImageGetHeight(image.CGImage);
                    [dic setValue:@((int)weight) forKey:@"weight"];
                    [dic setValue:@((int)height) forKey:@"height"];
                    data = imageModel.videoData;
                    
                }else if (imageModel.isImage){
                    UIImage * image =  imageModel.image;
                    CGFloat weight = CGImageGetWidth(image.CGImage);
                    CGFloat height = CGImageGetHeight(image.CGImage);
                    [dic setValue:@((int)weight) forKey:@"weight"];
                    [dic setValue:@((int)height) forKey:@"height"];
                    data = UIImagePNGRepresentation(image);
                }
            }
            
            if (data.length==0) {
                //                return nil;
            }
            
            OSSPutObjectRequest * put = [OSSPutObjectRequest new];
            put.bucketName = BL_ALI_BUCKET;//去阿里云控制台查看
            NSString * imagePath = [NSString stringWithFormat:@"%@/%@/%@.%@",[BLUserManager shareUser].userInfo.userId,[self getUpPathWithType:type],[BLTool getUuid],iamgeType];
            put.objectKey = imagePath;
            
            put.uploadingData= data;// 直接上传NSData
            put.uploadProgress= ^(int64_t bytesSent,int64_t totalByteSent,int64_t totalBytesExpectedToSend) {
                //                NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
            };
            OSSTask* putTask = [client putObject:put];
            [putTask continueWithBlock:^id(OSSTask*task) {
                //这一步很关键 缺少这一步运行会出错   里面的参数和上面一样
                task = [client presignPublicURLWithBucketName:BL_ALI_BUCKET withObjectKey:imagePath];
                NSLog(@"objectkey ========%@",put.objectKey);
                if(!task.error) {
                    
                    NSString * photoPath = task.result;
                    if (type != UpLoadImageType_Avatar) {
                        photoPath = [self URLDecodedString:photoPath];
                    }
                    
                    [dic setValue:photoPath forKey:@"photoPath"];
                    [array addObject:dic];
                    
                    dispatch_semaphore_signal(semaphore);
                    
                }else{
                    NSLog(@"upload object failed, error: %@" , task.error);
                    failure(task.error.localizedDescription);
                    // 每次发送信号则semaphore会+1，
                    dispatch_semaphore_signal(semaphore);
                }
                return nil;
            }];
            
        });
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); //-1
    }
    
    success([array copy]);
    
    //    dispatch_group_notify(group, queue, ^{
    //        success([array copy]);
    //    });
    
}

+ (NSString*) getGMTDate{
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval a=[dat timeIntervalSince1970];
    
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}

+ (void)getUserData{
    [BLHttpTool postWithPath:BL_USER_CENTER params:@{} successBlock:^(NSDictionary * _Nonnull obj) {
        BLInfoUserInfo *model = [BLInfoUserInfo mj_objectWithKeyValues:obj[@"content"]];
        
        [BLUserManager shareUser].userInfo = model;
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        
    }];
}

+ (void)loginWithCompletion:(void(^)(void))over{
    [BLTool loginWithCompletion:over fail:^{
        
    }];
}
+ (void)loginWithCompletion:(void(^)(void))over fail:(void(^)(void))fail{
    UIViewController *controller = [BLTool getCurrentViewController];
    BLLoginController *vc = [[BLLoginController alloc]init];
    BLNavigationController *nav = [[BLNavigationController alloc]initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
    vc.loginBlock = ^{
        [controller dismissViewControllerAnimated:YES completion:nil];
    };
    vc.onlyBlock = ^{
        [controller dismissViewControllerAnimated:YES completion:nil];
        if (over) {
            over();
        }
    };
    vc.failBlock = ^{
        if (fail) {
            fail();
        }
    };
    
    [controller presentViewController:nav animated:YES completion:nil];
}
+(UIViewController *)getCurrentViewController
{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIViewController *topViewController = [window rootViewController];
    
    while (true) {
        
        if (topViewController.presentedViewController) {
            
            topViewController = topViewController.presentedViewController;
            
        } else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
            
            topViewController = [(UINavigationController *)topViewController topViewController];
            
        } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
            
            UITabBarController *tab = (UITabBarController *)topViewController;
            topViewController = tab.selectedViewController;
            
        } else {
            break;
        }
    }
    return topViewController;
}

+(UINavigationController *)getCurrentNavigationController{
    UIViewController *control = [self getCurrentViewController];
    UINavigationController *nav = control.navigationController;
    return nav;
}

+(void)viewBeizerRect:(CGRect)rect view:(UIView *)view corner:(UIRectCorner)corner cornerRadii:(CGSize)radii{
    UIBezierPath *maskPath= [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radii];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame =view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
    
}

+(NSString *)getUuid{
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return  uuid;
}


/**
 *  URLEncode
 */
+(NSString *)URLEncodedString:(NSString *)str
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = str;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

/**
 *  URLDecode
 */
+(NSString *)URLDecodedString:(NSString *)urlString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)urlString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}





@end

@implementation BLImageModel
+(BLImageModel *)modelWithUIImage:(UIImage *)image{
    BLImageModel * model = [[BLImageModel alloc]init];
    model.image = image;
    return model;
}
@end
